﻿using System;
using System.Threading;
using System.Threading.Tasks;
using K9Nano.IM.Models;
using K9Nano.LayIM;
using K9Nano.LayIM.Models;
using K9Nano.LayIM.Stores;
using Microsoft.Extensions.Options;
using WalkingTec.Mvvm.Core;

namespace K9Nano.IM.LayIM
{
    public class ChatMessageStore: ChatStoreBase, IChatMessageStore
    {
        public ChatMessageStore(IDataContext db, IOptions<LayIMOptions> options) : base(db, options)
        {
        }
        
        public async Task<string> SaveAsync(string sessionId, LayIMSendMessage message, CancellationToken cancellation)
        {
            var chatMsg = new ChatMessage
            {
                Message = message.mine.content,
                Type = EChatMessageType.Text,
                FromId = Guid.Parse(message.mine.id),
                ToId = Guid.Parse(message.to.id),
            };

            if (Guid.TryParse(sessionId, out var sid))
            {
                chatMsg.SessionId = sid;
            }

            Db.AddEntity(chatMsg);

            await Db.SaveChangesAsync(cancellation);

            return chatMsg.ID.ToString();
        }
    }
}
